package com.sinosoft.bee.services.provider.demo.config;

import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.StringUtils;
import redis.clients.jedis.JedisPoolConfig;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@Configuration
@ConfigurationProperties(prefix = "redis.cluster")
@Setter
public class RedisClusterConfig {


    /**
     * 注入redis.cluster.servers
     */

    private String servers;
    private Integer maxRedirects;

    @Bean
    public RedisClusterConfiguration redisClusterConfiguration() {

        String[] redisNodes2String = StringUtils.commaDelimitedListToStringArray(servers);
        List<RedisNode> redisNodes = new ArrayList<RedisNode>();

        for (String str : redisNodes2String) {
            String[] temps = str.split(":");
            redisNodes.add(new RedisNode(temps[0], Integer.parseInt(temps[1])));
        }

        RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();
        redisClusterConfiguration.setMaxRedirects(maxRedirects);
        redisClusterConfiguration.setClusterNodes(redisNodes);
        return redisClusterConfiguration;
    }

    @Bean
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        return jedisPoolConfig;
    }


    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
        return new JedisConnectionFactory(redisClusterConfiguration(), jedisPoolConfig());
    }


    @Bean
    public RedisTemplate<String,Object> redisTemplate(){
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
        redisTemplate.setConnectionFactory(redisConnectionFactory());
        return  redisTemplate;
    }
}
